#pragma  once

#include "windows.h"
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <fstream>
#include <atlstr.h>
#include <string>


using namespace std;

/////////////////////////////////////////////////////////////////////////////
// CConsole:
// Tracing...
//

#define CONSOLE( Format, ... )	            		 \
		g_Console.Console( Format, __VA_ARGS__ );  

class CConsole
{
public:
	static const WORD MAX_CONSOLE_LINES = 1000;
	static const WORD MAX_LINE_WIDTH = 1000;

	CConsole()
	{
		AllocConsole();
		m_hConsole = GetStdHandle( STD_OUTPUT_HANDLE );

		//RedirectIOToConsole();
	}

	~CConsole()
	{
		m_hConsole = NULL;
		FreeConsole();
	}

	void Console( LPCTSTR lpszFormat, ... )
	{
		va_list args;
		
		CString string
        va_start( args, lpszFormat );
		string.FormatV( lpszFormat, args );
        va_end( args );

		
		if ( m_hConsole )
		{
			DWORD written;   
			WriteConsole( m_hConsole, (LPCTSTR)string, string.GetLength(), &written, 0 );
		}
	}


	void RedirectIOToConsole()
	{
		int hConHandle;
		long lStdHandle;

		CONSOLE_SCREEN_BUFFER_INFO coninfo;

		FILE *fp;

		// allocate a console for this app

		// set the screen buffer to be big enough to let us scroll text

		GetConsoleScreenBufferInfo(m_hConsole, &coninfo);

		coninfo.dwSize.Y = MAX_CONSOLE_LINES;
		coninfo.dwSize.X = MAX_LINE_WIDTH;

		SetConsoleScreenBufferSize(m_hConsole, coninfo.dwSize);

		// redirect unbuffered STDOUT to the console

		lStdHandle = (long)m_hConsole;
		hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
		fp = _fdopen( hConHandle, "w" );

		*stdout = *fp;
		setvbuf( stdout, NULL, _IONBF, 0 );


		// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog 
		// point to console as well
		ios::sync_with_stdio();
}


private:

	HANDLE m_hConsole;
};

extern CConsole g_Console;




/////////////////////////////////////////////////////////////////////////////


